package command.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;
import server.ClientThread;
import server.Server;

public class DisconnectConversationServer implements CommandServer {

    private boolean isDisconnectAtConversation = false;
    private String conversationID;
    private ArrayList<User> userList;

    public DisconnectConversationServer() {
    }

    public void setIsDisconnectAtConversation() {
        isDisconnectAtConversation = true;
    }

    public void setConversationID(String idOfTheConversation) {
        conversationID = idOfTheConversation;
    }

    public void setUserList(ArrayList<User> usersOfTheConversation) {
        userList = usersOfTheConversation;
    }

    @Override
    public void execute(ClientThread clientThread) {
        try {
            if (!isDisconnectAtConversation) {
                MessageCommunication message = (MessageCommunication) clientThread.getObjectInputStream().readObject();
                User u = (User) clientThread.getObjectInputStream().readObject();
                Server.removeUserAtConversation(message.getMessage(), u);
            } else {
                clientThread.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, "disconnectconversationclient"));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, conversationID));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(userList);
                clientThread.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(DisconnectConversationServer.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el abandono de una conversación por parte de un cliente", ex);
        }
    }
}
